<?php

namespace app\service\order;

use app\admin\model\user\User;
use app\common\model\Order as OrderModel;
use app\admin\model\order\PaysnLog as OrderPaysnLogModel;
use app\service\order\Recharge;
use think\facade\Db;

class Verify
{
    public function verify($order_sn = '', $pay_type = '', $paymentInfo = [], $transaction_id = '', $total_fee = 0)
    {
        $locKey = 'lock'.$order_sn;

        $redis = \think\facade\Cache::store('redis')->handler();
        $lock = $redis->get($locKey);
        if ($lock) {
            throw new \Exception("订单处理中");
        }

        $redis->setnx($locKey, 1);

        $paysnRow = OrderPaysnLogModel::where('pay_sn', $order_sn)->find();
        if (!$paysnRow) {
            $redis->del($locKey);
            throw new \Exception("订单未找到");
        }

        $order = OrderModel::find($paysnRow['order_id']);
        if (!$order) {
            $redis->del($locKey);
            throw new \Exception("订单未找到");
        }
        if ($order['status'] > 0) {
            $redis->del($locKey);
            return true;
        }

        if(!$total_fee){
            $total_fee = $order['payable_money'];
        }
        $user = \app\admin\model\User::where('id',$order['user_id'])->find();
        //使用事务
        Db::startTrans();
        try {
            $upOrder = [
                'pay_type' => $pay_type,
                'pay_status' => 1,
                'pay_time' => time(),
                'transaction_id' => $transaction_id,
            ];

            if (in_array($order['order_type'], [1,2])) {
                //如果是充值，则直接完成订单
                $upOrder['status'] = 3;
            } else {
                //商城订单改为已支付
                $upOrder['status'] = 1;
            }

            if (in_array($pay_type, ['wxpay', 'minipay', 'wxcode'])) {
                //微信要除以100
                $total_fee /= 100;
            }
            $upOrder['real_money'] = $total_fee;
            $res = $order->save($upOrder);
            if (!$res) {
                $redis->del($locKey);
                throw new \Exception("订单处理异常");
            }

            switch ($order['order_type']) {
                case 1:
                    $order_recharge = \app\admin\model\OrderRecharge::where('order_sn',$order['order_sn'])->find();
                    \app\admin\model\OrderRecharge::where('order_sn',$order['order_sn'])->update([
                        'pay_status' => 1,
                        'pay_time' => time()
                    ]);
                    $moneyLogService = new \app\service\user\UserMoneyLog();
                    $moneyLogService->changeMoney($order['user_id'], $order_recharge['charge_money'], 1, '充值', $order['order_sn']);
                    break;
                case 2:
                    $order_vip = \app\admin\model\OrderVip::where('order_sn',$order['order_sn'])->find();
                    \app\admin\model\OrderVip::where('order_sn',$order['order_sn'])->update([
                        'pay_status' => 1,
                        'pay_time' => time()
                    ]);
                    $user_vip = \app\admin\model\UserLevel::where('id',$order_vip['level_id'])->find();
                    if($user_vip){
                        if($user['is_vip']){//如果是会员
                            // 创建DateTime对象
                            $dateTime = new \DateTime(date('Y-m-d H:i:s',$user->expire_time));
                            $dateTime->modify(+$user_vip->duration.' month');
                            $upUser['expire_time'] = strtotime($dateTime->format('Y-m-d H:i:s'));
                        }else{
                            $dateTime = new \DateTime();
                            $dateTime->modify(+$user_vip->duration.' month');
                            $upUser = [
                                'is_vip' => 1,
                                'expire_time' => strtotime($dateTime->format('Y-m-d H:i:s')),
                            ];
                        }
                        \app\admin\model\User::where('id',$user['id'])->update($upUser);
                    }
                    break;
                case 3:
                    $orderCreate = new Recharge();
                    $orderCreate->rechargeOrderVerify($order);
                    break;
                default:
                    break;
            }
            // 记录支付信息
            $res = $paysnRow->save([
                'status' => 'paid',
                'real' => $total_fee,
                'pay_time' => time(),
                'pay_type' => $pay_type,
                'transaction_id' => $transaction_id,
                'payment_json' => json_encode($paymentInfo),
            ]);
            if (!$res) {
                $redis->del($locKey);
                throw new \Exception("订单处理异常");
            }
            Db::commit();
        } catch (\Exception $e) {   //捕获抛出的异常
            Db::rollback();
            \think\facade\Log::error("OrderverifyError:" .$e->getMessage());
            throw new \Exception("订单处理异常");
        } catch (\Error $e) {       //捕获语法。数据库语句级别异常
            Db::rollback();
            \think\facade\Log::error("OrderverifyError:" .$e->getMessage());
            throw new \Exception("订单处理异常");
        } finally{                  //无论是否抛出异常，此处代码会保活
            $redis->del($locKey);
        }
        return true;
    }

}